from flask import Blueprint, jsonify, request, redirect
import json
from db import db1

bp_courses = Blueprint('courses', __name__)
from .admin_user import get_data


def xtree(data):
    if not data:
        return data
    else:
        tree = {}
        list = []
        for i in data:
            tree[i['id']] = i
        for j in data:
            if j['pid'] == 0:
                list.append(j)
            else:
                if 'son' not in tree[j['pid']]:
                    tree[j['pid']]['son'] = []
                tree[j['pid']]['son'].append(j)
        return list


@bp_courses.route('/cates', methods=['POST', 'GET'])
def cates():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        if data['params']:
            sql = '''insert into cates values (0,'%s',%d,%s)''' % (data['name'], int(data['pid']), data['params'])
        else:
            sql = '''insert into cates values (0,'%s',%d,'%s')''' % (data['name'], int(data['pid']), '')
        db1.update(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        sql = '''select * from cates'''
        res = db1.findall(sql)
        # print(res)
        data = xtree(res)
        return jsonify({'code': 200, 'list': data})


@bp_courses.route('/pageM', methods=['GET'])
def pageM():
    if request.method == 'GET':
        capge = request.args.get('cpage')
        page_size = 3
        start = (int(capge) - 1) * page_size
        sql = 'select c.name,c.params,t.name as tname from cates as c left join cates as t on c.pid=t.id order by c.id asc limit %d,%d' % (
            start, page_size)
        sql2 = '''select count(id) from cates'''
        res = db1.findall(sql)
        total = db1.findone(sql2)
        return jsonify({'code': 200, 'list': res, 'total': total['count(id)']})


import time


@bp_courses.route('/tea', methods=['GET'])
def tea():
    if request.method == 'GET':
        time.sleep(0.1)
        sql = '''select * from teacher'''
        res = db1.findall(sql)
        return jsonify({'code': 200, 'tea': res})


@bp_courses.route('/cate', methods=['GET'])
def cate():
    if request.method == 'GET':
        id = request.args.get('id')
        sql = '''select params from cates where id=%d ''' % (int(id))
        res = db1.findone(sql)

        return jsonify({'code': 200, 'params': res['params']})


@bp_courses.route('/courses', methods=['POST', 'GET'])
def courses():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        if data['params']:
            sql = "insert into courses(id,title,pid,params,pic,descrip,teacher_id,status) values(0,'%s',%d,'%s','%s','%s',%d,%d)" % (
                data['title'], int(data['pid']), data['params'], data['pic'], data['descrip'], int(data['teacher_id']),
                int(data['status']))
        else:
            sql = "insert into courses(title,pid,pic,descrip,teacher_id,status) values('%s',%d,'%s','%s',%d,%d)" % (
                data['title'], int(data['pid']), data['pic'], data['descrip'], int(data['teacher_id']),
                int(data['status']))
        db1.update(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        cpage = request.args.get('cpage')
        if cpage:
            page_size = 2
            start = (int(cpage) - 1) * page_size
            sql = '''select c.id,c.title,c.pic,c.descrip,c.status,ca.name as caname from courses as c left join cates as ca on c.pid = ca.id limit %d,%d''' % (
                start, page_size)
        else:
            sql = '''select id,title from courses'''
        res = db1.findall(sql)
        sql2 = '''select count(id) from courses'''
        total = db1.findone(sql2)
        return jsonify({'code': 200, 'list': res, 'total': total['count(id)']})


from utils.comm import qntoken


@bp_courses.route('/qn', methods=['GET'])
def qn():
    if request.method == 'GET':
        token = qntoken()
        return jsonify({'code': 200, 'qntoken': token})


import os


@bp_courses.route('/addmp4', methods=['POST'])
def addmp4():
    if request.method == 'POST':
        file = request.files['file']
        courses_id = str(request.form['course_id'])
        print(courses_id)
        path = './static/upload/' + courses_id
        if not os.path.exists(path):
            os.mkdir(path)
        file.save(os.path.join(path, file.filename))
        return jsonify({'code': 200, 'url': path + '/' + file.filename})


@bp_courses.route('/jie', methods=['POST', 'GET'])
def jie():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = '''insert into jie values(0,"%s",%d,"%s")''' % (data['name'], data['course_id'], data['video_url'])
        db1.update(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        id = int(request.args.get('id'))
        sql = '''select j.id,j.name,j.video_url,c.title as ctitle from jie as j left join courses as c on j.course_id = c.id where course_id = %d''' % (
            id)
        res = db1.findall(sql)
        return jsonify({'code': 200, 'list': res})


@bp_courses.route('/active', methods=['POST', 'GET'])
def active():
    if request.method == 'POST':
        data = get_data()
        sql = 'insert into active(title,titlename,address,stime,total_time,t_count,price) values("%s","%s","%s","%s","%s",%d,%.1f)' % (
            data['title'], data['titlename'], data['address'], data['stime'], data['total_time'], int(data['t_count']),
            float(data['price']))
        print(sql)
        db1.update(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        sql = 'select * from active'
        res = db1.findall(sql)
        return jsonify({'code': 200, 'list': res})


@bp_courses.route('/record', methods=['POST'])
def record():
    if request.method == 'POST':
        data = get_data()
        # 先通过前端传的去用户表找
        sql0 = 'select * from active_record where mobile = "%s" and active_id = %d ' % (
            data['username'], int(data['id']))
        res0 = db1.findall(sql0)
        if res0:
            return jsonify({'code': 20010, 'mes': '不能重复参与'})
        # 根据训练营id查
        sql = 'select * from active where id = %d' % (int(data['id']))
        res = db1.findone(sql)
        sql1 = 'select * from users where username = "%s" ' % (data['username'])
        res1 = db1.findone(sql1)
        if res1:
            # 1能找到
            # 1.1超级用户直接填入record表
            if int(res1['level']) == 3:
                sql2 = 'insert into active_record(mobile,active_id,type,pay_status,money) values("%s",%d,1,2,0)' % (
                    data['username'], int(data['id']))
                res2 = db1.update(sql2)
                # 去更新训练营表中的剩余人数
                if int(res['use_count'] >= 0):
                    count = int(res['use_count']) - 1
                    sql3 = "update active set use_count=%d where id=%d" % (count, int(data['id']))
                    res3 = db1.update(sql3)
                return jsonify({'code': 200})
            # 1.2不是超级用户，返回无权限
            else:
                return jsonify({'code': 20011, 'mes': '不是VIP,垃圾'})
        # 2没找到
        else:
            # 生成订单返回
            acsql = "insert into active_record(mobile,active_id,type,pay_status,money) values('%s',%d,2,1,%.1f)" % (
                data['username'], int(data['id']), float(res['price']))
            db1.update(acsql)
            # 查询id
            sql4 = "select * from active_record where active_id=%d and mobile='%s'" % (
                int(data['id']), data['username'])
            res4 = db1.findone(sql4)
            return jsonify({"code": 2001, 'order_id': res4['id'], 'money': res4['money']})

            # 写入用户表并生成订单返回，调用支付


from utils.comm import get_ali_object
import time


@bp_courses.route('/pay', methods=['POST'])
def pay():
    if request.method == 'POST':
        data = get_data()
        order_id = data['id']
        sql = "select * from active_record where id =%d" % (int(order_id))
        res = db1.findone(sql)
        print('----')
        alipay = get_ali_object()

        # 生成支付的url
        query_params = alipay.direct_pay(
            subject="test",  # 商品简单描述
            out_trade_no="active"+res['id'],  # 用户购买的商品订单号（每次不一样） 20180301073422891
            total_amount=float(res['money'])  # 交易金额(单位: 元 保留俩位小数)
        )
        print('====')
        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
        print('+++++')
        return jsonify({'code': 200, 'url': pay_url})


@bp_courses.route('/notify/')
def alipay_callback():
    # 支付的时候传递给支付宝的订单号
    out_trade_no = request.args.get('out_trade_no')
    # 支付宝的流水号
    trade_no = request.args.get('trade_no')
    orderlist = out_trade_no.split(":")
    if orderlist[0] == 'active':
    # 根据out_trade_no查询active_record
        sql = "select * from active_record where id=%d" % (int(out_trade_no))
        res = db1.findone(sql)
        if res:
            # 更新支付状态为2，流水号为trade_no
            sql2 = "update active_record set pay_status=2,transaction='%s' where id = %d" % (str(trade_no), int(res['id']))
            db1.update(sql2)
            # 更新活动可用次数-1
            # 根据活动id查询活动信息
            sql1 = "select * from active where id=%d" % (int(res['active_id']))
            res1 = db1.findone(sql1)
            if int(res1['use_count']) >= 1:
                count = int(res1['use_count']) - 1
                sql2 = "update active set use_count=%d where id=%d" % (count, int(res['active_id']))
                db1.update(sql2)
                return redirect('http://127.0.0.1:8888/')
    elif orderlist[0] == 'vip':
        sql = "select * from vip_order where order_no= '%s'" % (orderlist[1])
        res = db1.findone(sql)
        if res:
            # 更新支付状态为2，流水号为trade_no
            sql2 = "update vip_order set pay_status=2,transaction='%s' where order_no = '%s'" % (
            str(trade_no),str(orderlist[1]))
            db1.update(sql2)
            sql3 = 'select v.type as type,v.day as day,vo.userid as userid from vip as v inner join vip_order as vo on v.id = vo.vip_id where vo.order_no = "%s"'%(orderlist[1])
            res3 = db1.findone(sql3)
            print(res3)
            sql4 = 'select * from vip_time where userid = %d'%(int(res3['userid']))
            res4 = db1.findone(sql4)
            if res4:


                etime = res4['etime']+datetime.timedelta(days=int(res3['day']))
                sql5 = 'update vip_time set etime = "%s" where id = %d'%(etime,int(res4['id']))
                db1.update(sql5)
            else:
                # stime = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S")
                if int(res3['type']) == 3:
                    stime = datetime.datetime.now()
                    etime = '9999-12-31 23:59:59'
                else:
                    stime = datetime.datetime.now()
                    etime = stime + datetime.timedelta(days=int(res3['day']))
                sql6 = 'insert into vip_time(stime,etime,type,userid) values("%s","%s",%d,%d)' % (
                stime, etime, 1, int(res['userid']))
                db1.update(sql6)
                sql7 = 'update users set level = %d where id = %d'%(int(res3['type']),int(res3['userid']))
                db1.update(sql7)
            return jsonify({'code':200})
        else:
            return jsonify({'code':20015,'mes':'查不到此订单'})


import datetime
import random

@bp_courses.route('/vip_list',methods=['GET','POST'])
def vip_list():
    if request.method == 'GET':
        sql = 'select * from vip'
        res = db1.findall(sql)
        return jsonify({'code':200,'list':res})
    elif request.method == 'POST':
        data = get_data()
        id = int(data['id'])
        sql1 = 'select * from vip where id = %d '%(id)
        res1 = db1.findone(sql1)


        order_no = str(datetime.datetime.strftime(datetime.datetime.now(),"%Y%m%d%H%M%S"))+str(data['userid'])+str(random.randint(100000,999999))
        sql2 = 'insert into vip_order(userid,order_no,vip_id,money,pay_status) values(%d,"%s",%d,%d,%d)'%(int(data['userid']),order_no,int(data['id']),res1['money'],1)
        db1.update(sql2)
        alipay = get_ali_object()

        # 生成支付的url
        query_params = alipay.direct_pay(
            subject="test",  # 商品简单描述
            out_trade_no="vip:"+order_no,  # 用户购买的商品订单号（每次不一样） 20180301073422891
            total_amount=int(res1['money'])  # 交易金额(单位: 元 保留俩位小数)
        )
        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
        return jsonify({'code':200,'url':pay_url})


@bp_courses.route('/courseinfo',methods=['GET'])
def courseinfo():
    if request.method =='GET':
        id = request.args.get('id')
        sql = 'select c.title,c.params,c.descrip,c.gz_count,t.name,t.total_count from courses as c inner join teacher as t on c.teacher_id = t.id where c.id = %d'%(int(id))
        courses = db1.findone(sql)
        sql2 = 'select * from jie where course_id = %d order by id'%(int(id))
        jie = db1.findone(sql2)
        courses['jie'] = jie
        return jsonify({'code':200,'list':courses})